package controllers

import (
	"fmt"
	"math/rand"
	"net/http"
	"time"

	"shop-backend/internal/config"
	models "shop-backend/internal/order/ordermodels"

	"github.com/gin-gonic/gin"
)

// 下单请求结构体
type CreateOrderRequest struct {
	UserID   uint `json:"user_id" binding:"required"`
	Products []struct {
		ProductID uint    `json:"product_id" binding:"required"`
		Quantity  int     `json:"quantity" binding:"required"`
		Price     float64 `json:"price" binding:"required"`
	} `json:"products" binding:"required"`
}

// 创建订单
func CreateOrder(c *gin.Context) {
	var req CreateOrderRequest
	// 绑定 JSON 数据到 req
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
		return
	}

	// 生成订单号（时间戳+随机数）
	orderNumber := fmt.Sprintf("%d%04d", time.Now().Unix(), rand.Intn(10000))

	// 创建订单数据
	order := models.Order{
		OrderNumber: orderNumber,
		UserID:      req.UserID,
		Status:      "submitted",
		TotalPrice:  0,
	}

	// 计算总价 & 保存订单
	for _, item := range req.Products {
		order.TotalPrice += float64(item.Quantity) * item.Price
	}

	if err := config.DB.Create(&order).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "订单创建失败"})
		return
	}

	// 保存订单明细
	for _, item := range req.Products {
		orderItem := models.OrderItem{
			OrderID:   order.ID,
			ProductID: item.ProductID,
			Quantity:  item.Quantity,
			Price:     item.Price,
		}
		config.DB.Create(&orderItem)
	}

	c.JSON(http.StatusOK, gin.H{"message": "下单成功", "order_number": orderNumber})
}
